using System;
using UnityEditor;
using UnityEngine;

namespace Gj
{
    [CustomPropertyDrawer(typeof(RefField))]
    public class RefFieldDrawer: PropertyDrawer
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent content)
        {
            string type = ((RefField)attribute).type;
            bool isKey = ((RefField) attribute).isKey;
            string value = "0";
            string label = "";
            string _value = "0";
            string _label = "";
            switch (property.propertyType)
            {
                case SerializedPropertyType.Generic:
                    value = isKey ? property.FindPropertyRelative("key").stringValue : property.FindPropertyRelative("id").intValue.ToString();
                    label = property.FindPropertyRelative("name").stringValue;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            
            switch (property.propertyType)
            {
                case SerializedPropertyType.Generic:
                    content = EditorGUI.BeginProperty(position, content, property);
                    var contentPosition = EditorGUI.PrefixLabel(position, content);
                    EditorGUIUtility.labelWidth = 1f;
                    contentPosition.width /= 2f;
                    _value = EditorGUI.DelayedTextField(contentPosition, content, value);
                    contentPosition.x += contentPosition.width;
                    _label = EditorGUI.DelayedTextField(contentPosition, content, label);
                    EditorGUI.EndProperty();
                    if (!string.IsNullOrEmpty(_value) && !string.IsNullOrEmpty(_label)) RefData.SetRef(type, value, label, _value, _label);
                    if (isKey)
                    {
                        property.FindPropertyRelative("key").stringValue = _value;
                    }
                    else
                    {
                        property.FindPropertyRelative("id").intValue = Convert.ToInt32(_value);
                    }
                    property.FindPropertyRelative("name").stringValue = _label;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
}